<?php 
// +----------------------------------------------------------------------
// | RXThinkCMF敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 RXThinkCMF并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: @牧羊人 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\admin\service\SportService;
use think\Db;
use think\Request;
use app\admin\model\Member;
use app\admin\model\Project;
use app\admin\model\Task;
use app\admin\model\Match;
use app\admin\model\Standard;
use app\admin\model\Equipment;
use app\admin\model\Clss;
use app\admin\model\BraceletLog;
use app\admin\model\SportRecord;

use app\admin\service\LoginService;

/**
 * 测试-控制器
 * @author 牧羊人
 * @since: 2023/08/03
 * Class Task
 * @package app\admin\controller
 */
class Test extends Backend
{
    /**
     * 初始化方法
     * @author 牧羊人
     * @since: 2023/08/03
     */
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->service = new LoginService();
    }

     public function aaa(){
         $standard     = (new Standard)->where(['name' => 'BMI'])->value('standard');
         $sportService = new SportService;
         $height = 153 / 100;
         $bmi =
              pro_float(round(45 / $height / $height, 2))
         ;
       
        $res = $sportService->standardCalc(
             $standard,
             $bmi,
             2
         );
        print_r($res);
        //cacl_bmi();
     }

    /**
     * 同步运动记录
     * @return mixed
     * @since 2020/11/20
     * @author 牧羊人
     */
    public function tongbuSport()
    {
        // 最近一天开始
        //$startTime = strtotime('-1 day')*1000; // 将日期转换为毫秒时间戳
        $startTime = strtotime('2024-05-15 00:00:00')*1000;
        // 当前时间
        //$endTime = time()*1000; // 将日期和时间转换为毫秒时间戳
        $endTime = strtotime('2024-05-15 23:59:59')*1000;
        $types = [1,2];//数据类型 1：校内体育测试 2：校内体育锻炼 3：校外体育云作业 4：校园云体锻
        $tbnum = 0;
        $data = [];
        foreach ($types as $v) {
            $datas = [
                "type"=>$v, 
                "startTimestamp"=> $startTime,
                "endTimestamp"=> $endTime,
                "pageNo"=> 1,
                "pageSize"=> 1000
            ];
            $result = $this->service->synchronousResult($datas);//获取第三方同步数据
            // halt($result);
            $clss = new Clss();
            $member = new Member();
            $project = new Project();
            $task = new Task();
            $match = new Match();
            $standard = new Standard();
            $rows = [];
            if (isset($result['result']['rows'])) {
               $rows = $result['result']['rows'];
            }
            foreach ($rows as &$vs) {
                $mlist = $member->where('roll',$vs['testerNumber'])->find();
                if ($mlist) { //判断匹配学籍号
                    $vs['type'] = $v;
                    $vs['tbid'] = $vs['id'];
                    $vs['memberId'] = $mlist['id'];
                    $vs['schoolId'] = $mlist['organization'];
                    $vs['gradeId'] = $mlist['grade'];
                    $vs['classId'] = $mlist['class'];
                    $vs['departmentsId'] = $mlist['superior'];
                    $vs['tiyu_superior'] = $mlist['tiyu_superior'];
                    $vs['professionalId'] = $mlist['professional'];
                    $vs['tiyu_professional'] = $mlist['tiyu_professional'];
                    $vs['tiyu_class'] = $mlist['features']?intval(json_decode($mlist['features'],true)[0]):0;
                    $vs['tiyu_class_string'] = $mlist['features'];
                    $vs['projectId'] = $project->where(['organization'=>$vs['schoolId'],'code'=>$vs['itemCode']])->value('id');
                    if ($vs['itemCode']=='weight'||$vs['itemCode']=='height') {
                        $vs['projectId'] = $project->where(['organization'=>$vs['schoolId'],'code'=>'BMI'])->value('id');
                    }
                    $stanArr = [];
                    if ($v==1) {//体测数据
                         $sta = $task->where('task_start','<=',$vs['startTime'])->where('task_end','>=',$vs['endTime'])->where('project',$vs['projectId'])->where('status',1)->where('mark',1)->find();
                         
                         if ($sta) {
                             if ($sta['class']) {
                                    $vs['tiyu_class'] = 0;
                                    $clssarr = json_decode($sta['class'],true);
                                    foreach ($clssarr as $val) {
                                        $str = '"'.$vs['memberId'].'"';
                                        $df = $clss->where('id',intval($val))->where('features','like','%'.$str.'%')->value('id');
                                        if ($df) {
                                            $vs['tiyu_class'] = intval($val);
                                            $vs['taskId'] = $sta['id']; //任务id
                                        }else{
                                            $vs['tiyu_class'] = 0;
                                            $vs['taskId'] = 0;
                                        }
                                    }  
                             }
                             $vs['model'] = $sta['model']; //任务模式
                             $stanArr = json_decode($standard->where('id',$sta['standard'])->value('standard'),true);
                         }else{
                            $mat = $match->where('begin_time','<=',strtotime($vs['startTime']))->where('end_time','>=',strtotime($vs['endTime']))->where('projectId',$vs['projectId'])->where('mark',1)->find();
                            if ($mat['mtype']==1) {
                                $vs['type'] = 3; //体育赛事
                            }

                            if ($mat['mtype']==2) {
                                $vs['type'] = 4; //院系测试
                            }
                            
                            if ($mat) {
                                $stanArr = json_decode($standard->where('project',$mat['projectId'])->value('standard'),true);
                                $vs['taskId'] = $mat['id']; //赛事id
                            }else{
                                $vs['taskId']=0;
                                $vs['type'] = 2; //体锻数据
                                $pid = $project->where(['code'=>$vs['itemCode']])->value('id');
                                if ($pid) {
                                    $stanArr = json_decode($standard->where(['organization'=>$vs['schoolId'],'project'=>$pid])->value('standard'),true);
                                }

                            }
                         }
                    }
                    if ($v==2) {//体锻数据
                        $pid = $project->where(['code'=>$vs['itemCode']])->value('id');
                        if ($pid) {
                            $stanArr = json_decode($standard->where(['organization'=>$vs['schoolId'],'project'=>$pid])->value('standard'),true);
                        }
                        
                    }
                    if ($stanArr) {
                        foreach ($stanArr as $vv) {
                             if ($vv['sex']==$mlist['gender']) {
                                switch ($vv['conditions']) {//判断成绩评级
                                    case 'gt':
                                        if ($vs['score']>$vv['target'][0]) {
                                            $vs['rating'] = $vv['level'];
                                            $vs['pingscore'] = $vv['score'];
                                        }
                                        break;
                                    case 'egt':
                                        if ($vs['score']>=$vv['target'][0]) {
                                            $vs['rating'] = $vv['level'];
                                            $vs['pingscore'] = $vv['score'];
                                        }
                                        break;
                                    case 'lt':
                                        if ($vs['score']<$vv['target'][0]) {
                                            $vs['rating'] = $vv['level'];
                                            $vs['pingscore'] = $vv['score'];
                                        }
                                        break;
                                    case 'elt':
                                        if ($vs['score']<=$vv['target'][0]) {
                                            $vs['rating'] = $vv['level'];
                                            $vs['pingscore'] = $vv['score'];
                                        }
                                        break;
                                    case 'between':
                                        if ($vs['score']>=$vv['target'][0]&&$vs['score']<=$vv['target'][1]) {
                                            $vs['rating'] = $vv['level'];
                                            $vs['pingscore'] = $vv['score'];
                                        }
                                        break;
                                    
                                    default:
                                        $vs['rating'] = 0;
                                        break;
                                }
                             }
                         }
                    }
                    //归类统计
                    $vs['stype'] = $project->where(['organization'=>$vs['schoolId'],'code'=>$vs['itemCode']])->value('type');
                    $vs['gender'] = $vs['gender']=='M'?1:2;
                    if (isset($vs['videoUrlList'])) {
                        $vs['videoUrlList'] = json_encode($vs['videoUrlList']);
                    }
                    $data[] = $vs;
                }
            }
            unset($vs);
        }
        $sportrecord = new SportRecord();
        foreach ($data as $vv) {
            $tbid = $vv['tbid'];
            $id = $sportrecord->where('tbid',$tbid)->value('id');
            if (!$id) {
                $sportrecord->allowField(true)->insert($vv);
            }else{
                $up = $vv;
                $sportrecord->allowField(true)->update($up);
            }
            $tbnum++;
        }
        unset($vv);
        //计算BMI结果
        cacl_bmi();
        echo "同步".$tbnum."条";
    }

    public function test2()
    {
        cacl_bmi();
    }

}